<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <div slot="title" v-if="!dataForm.id">{{$t('message.add')}}</div>
    <div slot="title" v-if="dataForm.id">{{$t('message.edit')}}</div>
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="140px">
      <el-form-item :label="$t('message.userName')" prop="userName">
        <el-input v-model="dataForm.userName" :placeholder="$t('message.loginAccount')"></el-input>
      </el-form-item>
      <el-form-item :label="$t('message.password')" prop="password" :class="{ 'is-required': !dataForm.id }">
        <el-input v-model="dataForm.password" :placeholder="$t('message.password')"></el-input>
      </el-form-item>
      <el-form-item :label="$t('message.passwordConfirm')" prop="comfirmPassword" :class="{ 'is-required': !dataForm.id }">
        <el-input v-model="dataForm.comfirmPassword" :placeholder="$t('message.passwordConfirm')"></el-input>
      </el-form-item>
      <el-form-item :label="$t('message.email')" prop="email">
        <el-input v-model="dataForm.email" :placeholder="$t('message.email')"></el-input>
      </el-form-item>
      <el-form-item :label="$t('message.phoneNo')" prop="mobile">
        <el-input v-model="dataForm.mobile" :placeholder="$t('message.phoneNo')"></el-input>
      </el-form-item>
      <el-form-item :label="$t('message.company')" prop="company">
        <el-input v-model="dataForm.company" :placeholder="$t('message.company')"></el-input>
      </el-form-item>
      <el-form-item :label="$t('message.contact')" prop="contact">
        <el-input v-model="dataForm.contact" :placeholder="$t('message.contact')"></el-input>
      </el-form-item>
      <el-form-item :label="$t('message.role')" size="mini" prop="roleIdList">
        <el-checkbox-group v-model="dataForm.roleIdList">
          <el-checkbox v-for="role in roleList" :key="role.roleId" :label="role.roleId">{{ role.roleName }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item :label="$t('message.status')" size="mini" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="0">{{$t('message.disable')}}</el-radio>
          <el-radio :label="1">{{$t('message.ok')}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('message.country')" prop="countryId" :class="{ 'is-required': true }">
        <el-select v-model="dataForm.countryId" @change="changeCountry(dataForm.countryId)">
          <el-option v-for="item in countries" :key="item.id" :label="item.title" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item v-show="provinceShow" :label="$t('message.province')" prop="provinceId" :class="{ 'is-required': true }">
        <el-select v-model="dataForm.provinceId"  @change="changeProvince(dataForm.provinceId)">
          <el-option v-for="item in provinceList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item v-show="provinceShow" :label="$t('message.city')" prop="cityId" :class="{ 'is-required': true }">
        <el-select v-model="dataForm.cityId"  @change="changeCity(dataForm.cityId)">
          <el-option v-for="item in cityList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item v-show="provinceShow" :label="$t('message.district')" prop="districtId" :class="{ 'is-required': true }">
        <el-select v-model="dataForm.districtId">
          <el-option v-for="item in districtList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{$t('message.cancle')}}</el-button>
      <el-button type="primary" @click="dataFormSubmit()">{{$t('message.submit')}}</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import { isEmail, isMobile } from '@/utils/validate'
  export default {
    data () {
      var validatePassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          callback(new Error(this.$t('message.passwordNoEmpty')))
        } else {
          callback()
        }
      }
      var validateComfirmPassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          callback(new Error(this.$t('message.confirmPasswordNoEmpty')))
        } else if (this.dataForm.password !== value) {
          callback(new Error(this.$t('message.passwordNotSame')))
        } else {
          callback()
        }
      }
      var validateEmail = (rule, value, callback) => {
        if (!isEmail(value)) {
          callback(new Error(this.$t('message.emailError')))
        } else {
          callback()
        }
      }
      var validateMobile = (rule, value, callback) => {
        if (!isMobile(value)) {
          callback(new Error(this.$t('message.phoneWrong')))
        } else {
          callback()
        }
      }
      return {
        visible: false,
        roleList: [],
        countries: [],
        provinceShow: false,
        provinceList: [],
        cityList: [],
        districtList: [],
        dataForm: {
          id: 0,
          userName: '',
          password: '',
          comfirmPassword: '',
          salt: '',
          email: '',
          mobile: '',
          company: '',
          contact: '',
          roleIdList: [],
          status: 1,
          countryId: '',
          provinceId: '',
          cityId: '',
          districtId: ''
        },
        dataRule: {
          userName: [
            { required: true, message: this.$t('message.noEmpty'), trigger: 'blur' }
          ],
          password: [
            { validator: validatePassword, trigger: 'blur' }
          ],
          comfirmPassword: [
            { validator: validateComfirmPassword, trigger: 'blur' }
          ],
          email: [
            { required: true, message: this.$t('message.noEmpty'), trigger: 'blur' },
            { validator: validateEmail, trigger: 'blur' }
          ],
          // mobile: [
          //   { required: true, message: this.$t('message.noEmpty'), trigger: 'blur' },
          //   { validator: validateMobile, trigger: 'blur' }
          // ],
          company: [
            { required: true, message: this.$t('message.noEmpty'), trigger: 'blur' }
          ],
          contact: [
            { required: true, message: this.$t('message.noEmpty'), trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      init (id) {
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
        })
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/sys/user/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.dataForm.userName = data.user.username
              this.dataForm.salt = data.user.salt
              this.dataForm.email = data.user.email
              this.dataForm.mobile = data.user.mobile
              this.dataForm.roleIdList = data.user.roleIdList
              this.dataForm.status = data.user.status
              this.dataForm.company = data.user.company
              this.dataForm.contact = data.user.contact
              this.dataForm.countryId = data.user.countryId
              this.dataForm.provinceId = data.user.provinceId
              this.dataForm.cityId = data.user.cityId
              this.dataForm.districtId = data.user.districtId
              this.roleList = data.roleList
              this.countries = data.countries
              this.provinceList = data.provinceList
              this.cityList = data.cityList
              this.districtList = data.districtList
              if (this.dataForm.countryId === 1) {
                this.provinceShow = true
              } else {
                this.provinceShow = false
              }
            }
          })
        } else {
          this.$http({
            url: this.$http.adornUrl(`/sys/user/regionInfo`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.countries = data.countries
              this.provinceList = data.provinceList
              this.roleList = data.roleList
            }
          })
        }
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if (this.dataForm.length > 1) {
              this.$message.error(this.$t('message.multiRoleError'))
            } else {
              this.$http({
                url: this.$http.adornUrl(`/sys/user/${!this.dataForm.id ? 'save' : 'update'}`),
                method: 'post',
                data: this.$http.adornData({
                  'userId': this.dataForm.id || undefined,
                  'username': this.dataForm.userName,
                  'password': this.dataForm.password,
                  'salt': this.dataForm.salt,
                  'email': this.dataForm.email,
                  'mobile': this.dataForm.mobile,
                  'status': this.dataForm.status,
                  'roleIdList': this.dataForm.roleIdList,
                  'company': this.dataForm.company,
                  'contact': this.dataForm.contact,
                  'countryId': this.dataForm.countryId,
                  'provinceId': this.dataForm.provinceId,
                  'cityId': this.dataForm.cityId,
                  'districtId': this.dataForm.districtId,
                  'deleteFlag': 1
                })
              }).then(({data}) => {
                if (data && data.code === 0) {
                  this.$message({
                    message: this.$t('message.success'),
                    type: 'success',
                    duration: 500,
                    onClose: () => {
                      this.visible = false
                      this.$emit('refreshDataList')
                    }
                  })
                } else {
                  this.$message.error(this.$t('message.failure'))
                }
              })
            }
          }
        })
      },
      changeCountry (countryId) {
        this.dataForm.provinceId = ''
        this.dataForm.cityId = ''
        this.dataForm.districtId = ''
        if (countryId === 1) {
          this.provinceShow = true
        } else {
          this.provinceShow = false
        }
      },
      changeProvince (provinceId) {
        this.dataForm.cityId = ''
        this.dataForm.districtId = ''
        this.$http({
          url: this.$http.adornUrl(`/sys/user/queryCityListByProvince`),
          method: 'post',
          data: this.$http.adornData({
            'provinceId': this.dataForm.provinceId
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.cityList = data.cityList
          } else {
            this.$message.error(this.$t('message.failure'))
          }
        })
      },
      changeCity (cityId) {
        this.dataForm.districtId = ''
        this.$http({
          url: this.$http.adornUrl(`/sys/user/queryDistrictListByCity`),
          method: 'post',
          data: this.$http.adornData({
            'cityId': this.dataForm.cityId
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.districtList = data.districtList
          } else {
            this.$message.error(this.$t('message.failure'))
          }
        })
      }
    }
  }
</script>
